<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" placeholder="用户名" style="width: 150px; margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.userPhone" placeholder="电话" style="width: 150px; margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%; "
      @sort-change="sortChange"
    >
      <!-- 渲染表单 -->
      <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="编号" width="60px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.userId }}</span>
          </template>
        </el-table-column> -->
      <el-table-column label="用户名" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="密码" width="280px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.password }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="60px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.gender }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="60px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生日" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.birthDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.roleId }}</span>
        </template>
      </el-table-column>
      <!-- 表单内部按钮 -->
      <el-table-column :label="$t('table.actions')" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!--修改的表单-->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户ID">
          <el-input
            v-model="temp.userId"
            :autosize="{ minRows: 2, maxRows: 4}"
            retype="text"
            readonly=""
          />
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="temp.username" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="用户姓名" />
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="temp.password" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="用户密码" />
        </el-form-item>
        <el-form-item label="用户年龄">
          <el-input v-model="temp.age" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="用户年龄" />
        </el-form-item>
        <el-form-item label="用户性别">
          <el-input v-model="temp.gender" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="用户性别" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker v-model="temp.birthDate" type="date" placeholder="请输入创建时间" />
        </el-form-item>
        <el-form-item label="用户电话">
          <el-input v-model="temp.phone" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="用户电话" />
        </el-form-item>
        <el-form-item label="用户邮箱">
          <el-input v-model="temp.email" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="用户邮箱" />
        </el-form-item>
        <el-form-item label="用户角色">
          <el-input v-model="temp.roleId" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="用户角色" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findByPage, addUser, deleteUser, updateUser } from '@/api/account'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {

  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {

  },
  data() {
    return {
      tableKey: 0,
      list: null, // 表格集合数据
      total: 0, // 总条数
      listLoading: true, // 是否被加载 true未被加载
      listQuery: { // 查询的筛选条件
        page: 1, // 页数
        limit: 10, // 每页条数
        userPhone: undefined,
        username: undefined
      },

      temp: { // 修改信息
        userId: undefined,

        username: '',
        password: '',
        age: '',
        gender: '',
        birthDate: '',
        phone: '',
        email: '',
        roleId: ''
      },
      dialogFormVisible: false, // (增加或者修改)表单是否打开 默认不打开
      dialogStatus: '', // 是修改还是增加
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        userName: [{ required: true, message: 'type is required', trigger: 'change' }],
        tiuserPhone: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {

    getList() { // 获取 list  total
      // 设置未加载
      this.listLoading = true
      // Axios请求后端
      findByPage(this.listQuery).then(response => {
        // console.log(response.data.list)
        // console.log(response.data.list[1].userName)
        this.list = response.data.list
        // console.log(this.list)
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 10)
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    // 重置数据
    resetTemp() {
      this.temp = {
        userId: undefined,
        username: '',
        password: '',
        age: '',
        gender: '',
        birthDate: '',
        phone: '',
        email: '',
        roleId: ''
      }
    },
    // 点击添加按钮调用的事件
    handleCreate() {
      this.resetTemp()// 重置数据
      this.dialogStatus = 'create'// 表单状态为 添加
      this.dialogFormVisible = true// 打开表单
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    // 添加用户
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        this.formatDate()
        if (this.temp.roleId == '管理员') {
          this.temp.roleId = 1
        } else if (this.temp.roleId == '用户') {
          this.temp.roleId = 2
        }
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          addUser(this.temp).then(() => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 点击表格内部修改按钮调用的事件
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 点击表单内部按钮是 修改的触发事件
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        this.formatDate()
        if (this.temp.roleId == '管理员') {
          this.temp.roleId = 1
        } else if (this.temp.roleId == '用户') {
          this.temp.roleId = 2
        }
        if (valid) {
          // 临时数据   temp内容拷贝到tempData
          const tempData = Object.assign({}, this.temp)
          // tempData 格式转换
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateUser(tempData).then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // 替换
            // 重新查询表格数据
            this.getList()
            // 关闭表单
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteUser(row.userId).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
      // this.list.splice(index, 1)
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    formatDate() {
      // 确保 birthDate 是一个 Date 对象
      if (typeof this.temp.birthDate === 'string') {
        this.temp.birthDate = new Date(this.temp.birthDate) // 转换为 Date 对象
      }

      // 确保 birthDate 是有效的 Date 对象
      if (this.temp.birthDate instanceof Date && !isNaN(this.temp.birthDate)) {
        this.temp.birthDate = this.temp.birthDate.toISOString().split('T')[0] // 转换为 yyyy-MM-dd 格式
      } else {
        console.error('Invalid date format') // 处理无效日期的情况
      }
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

